package cn.good.user.controller;

import cn.good.dto.Dto;
import cn.good.dto.DtoUtil;
import cn.good.user.service.QGUserService;
import cn.good.utils.Constant;
import cn.good.vo.TokenVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;


@Api(value="/api", tags="用户接口模块")
@RestController
@RequestMapping("/api")
public class UserController {

    @Resource
    private QGUserService qgUserService;

    @RequestMapping(value = "/baidu",method = RequestMethod.GET)
    public void gotoBaiDu(HttpServletResponse response){

        try {
            response.sendRedirect("http://www.baidu.com");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 用户登录
     * @param name
     * @param password
     * @param request
     * @return
     */
    @ApiOperation(value="用户登录实现",httpMethod = "POST", protocols = "HTTP", produces = "application/json", response = Dto.class,notes="用户登录")
    @RequestMapping(value = "/dologin", method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto login(@RequestParam String name, @RequestParam String password, HttpServletRequest request){
        String token = null;
        try {
            token = qgUserService.getUserByUserCode(name,password);
        } catch (Exception e) {
            return DtoUtil.returnFail(e.getMessage(),"100001");
        }
        TokenVo tokenVo = new TokenVo(token,Calendar.getInstance().getTimeInMillis()+ Constant.TOKEN_VALID_TIME,Calendar.getInstance().getTimeInMillis());
        return DtoUtil.returnDataSuccess(tokenVo);
    }
    /**
     * 注销
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value="用户注销实现",httpMethod = "GET", protocols = "HTTP", produces = "application/json", response = Dto.class,notes="用户注销")
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    @ResponseBody
    public Dto logout(HttpServletRequest request) throws Exception {
        try {
            qgUserService.logOut(request.getHeader("token"));
        } catch (Exception e) {
            return DtoUtil.returnFail("注销失败","100004");
        }
        return DtoUtil.returnSuccess("注销成功！");
    }
}
